
import common from "./libs/common";
import sendInfo from "./axios/axios";
import checkWord from "./libs/checkWords";


let fun = {
  power: false,
  list: [],
  needSendList: [],
  loopTimes: 0,
  readySend() {
    let newWord = this.list.shift().substring(0,20);
    // this.needSendList 
    console.log("readySend", newWord);
    const res = sendInfo(newWord);
    console.log("readySend res", res);
  },
  async loopSend() {
    await common.sleep(1000);
    this.loopTimes++;
    console.log(`第${this.loopTimes}次判断`);
    if (this.list.length) {
      this.readySend();
    }
    return this.loopSend();
    // console.log(this.list);
    // console.log(newWord);
  },
  slice20(data) {
    console.log("slice20", data);
    let arr = [];
    data.forEach(ele => {
      arr = [...arr, ...this.fixedLengthFormatString(ele, 20)];
    });
    console.log("slice20", arr);
    return arr;
  },
  /**
   * 按指定长度分段字符串
   * @param str 传入的字符串(非空)
   * @param num 指定长度(正整数)
   * @returns Array(字符串数组)
   */
  fixedLengthFormatString(str,num){
    if(str == null || str == undefined) return null;
    if(!(/^[0-9]*[1-9][0-9]*$/.test(num))) return null;
    var array = new Array();
    var len = str.length;
    for(var i=0;i<(len/num);i++){
      if((i+1)*num > len){
        array.push(str.substring(i*num,len));
      }else{
        array.push(str.substring(i*num,(i+1)*num));
      }
    }
    return array;
  },
  init(words) {
    /**
     * 1. 根据words获取最新列表
     * 2. 和当前队列合并并去重
     */
    try {
      console.log(1);
      let needSend = checkWord.checkKeywords(words);
      console.log(2);
      console.log("needSend", needSend);
      // needSend = [...this.list, ...needSend];
      let set = new Set(needSend);

      set = this.slice20([...set]);
      this.list = [...this.list, ...set];
      console.log("finList", this.list);
      
      // 若未启动则启动loop
      if (!this.power) {
        this.power = true;
        this.loopSend();
      }
    } catch (e) {
      console.log(e);
    }
  }
}
module.exports = fun;
